package com.zhangxin.sunnyweather.ui.Place

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhangxin.sunnyweather.R
import com.zhangxin.sunnyweather.WeatherActivity

class PlaceFragment : Fragment() {


    val viewModel by lazy { ViewModelProvider(this)[PlaceViewModel::class.java] }
    lateinit var recyclerView: RecyclerView
    lateinit var adapter: PlaceAdapter
    lateinit var searchPlaceEdit: EditText
    lateinit var bgImageView: ImageView


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("TEST LOG", "onCreateView: TEST LOG ")
        return inflater.inflate(R.layout.fragment_place, container, false)
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (viewModel.isPlaceSaved()) {
            val place = viewModel.getSavedPlace()
            val intent = Intent(context, WeatherActivity::class.java).apply {
                putExtra("location_lng", place.location.lng)
                putExtra("location_lat", place.location.lat)
                putExtra("place_name", place.name)
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }

        Log.d("TEST LOG", "onCreateView: TEST LOG ")

        recyclerView = view.findViewById(R.id.recyclerView)
        searchPlaceEdit = view.findViewById(R.id.searchPlaceEdit)
        bgImageView = view.findViewById(R.id.bgImageView)

        adapter = PlaceAdapter(this, viewModel.placeList)
        val layoutManager = LinearLayoutManager(activity)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        searchPlaceEdit.addTextChangedListener(object : TextWatcher { // 添加TextWatcher监听器到EditText
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化之前调用，可以不做处理
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 在文本变化时调用
                val content = s?.toString() // 获取当前文本内容
                if (!content.isNullOrEmpty()) { // 如果文本非空
                    viewModel.searchPlaces(content) // 调用ViewModel的搜索方法
                } else { // 如果文本为空
                    recyclerView.visibility = View.GONE // 隐藏RecyclerView
                    bgImageView.visibility = View.VISIBLE // 显示背景图片
                    viewModel.placeList.clear() // 清空ViewModel中的地点列表
                    adapter.notifyDataSetChanged() // 通知适配器数据已更改
                }
            }

            override fun afterTextChanged(s: Editable?) {
                // 在文本变化之后调用，可以不做处理
            }
        })

        viewModel.placeLiveData.observe(viewLifecycleOwner) { result ->   // 观察ViewModel中的地点列表，然后修改view
            val places = result.getOrNull()
            // 观察placeLiveData，当数据变化时调用
            if (places != null) { // 如果数据不为空
                recyclerView.visibility = View.VISIBLE // 显示RecyclerView
                bgImageView.visibility = View.GONE // 隐藏背景图片
                viewModel.placeList.clear() // 清空ViewModel中的地点列表
                viewModel.placeList.addAll(places) // 将搜索到的地点列表添加到ViewModel中
                adapter.notifyDataSetChanged() // 通知适配器数据已更改
            }
        }

    }
//
//    override fun onResume() {
//        super.onResume()
//        searchPlaceEdit.requestFocus()
//    }
}


